package com.lynn.demo;

import com.lynn.demo.lock.AquiredLockWorker;
import com.lynn.demo.lock.DistributedLocker;
import com.lynn.demo.lock.RedisLocker;
import com.lynn.demo.zk.DistributedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("index")
    public String index()throws Exception{
        System.out.println("-------------使用zookeeper进行分布式锁");
        DistributedLock lock   = new DistributedLock("localhost:2181","lock");
        lock.lock();
        //共享资源
        if(lock != null){
            System.out.println("执行方法");
            Thread.sleep(5000);
            lock.unlock();
        }
        return "hello world!";
    }

    @Autowired
    private DistributedLockHandler distributedLockHandler;

    @RequestMapping("index2")
    public String index2()throws Exception{
        System.out.println("-------------使用redis进行分布式锁");
        Lock lock= new Lock("lynn","min");
        if(distributedLockHandler.tryLock(lock)){
            try {
                //为了演示锁的效果，这里睡眠5000毫秒
                System.out.println("执行方法");
                Thread.sleep(5000);
            }catch (Exception e){
                e.printStackTrace();
            }
            distributedLockHandler.releaseLock(lock);
        }else{
            System.out.println("当前锁已经存在");
        }
        return "hello world2!";
    }

    @Autowired
    private DistributedLocker distributedLocker;
    @RequestMapping("index3")
    public String index3()throws Exception{
        System.out.println("-------------使用Redlock进行分布式锁");
        distributedLocker.lock("test",new AquiredLockWorker<Object>() {
            @Override
            public Object invokeAfterLockAquire() {
                try {
                    System.out.println("执行方法！");
                    Thread.sleep(5000);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return null;
            }

        });
        return "hello world3!";
    }
}
